/*********************************************************************
 * Módulo 3. Tutorial de desarrollo con NME. Sprites Animados. 
 * Programación Multimedia y Juegos
 * Autor: David Vallejo Fernández    david.vallejo@tegnix.com
 * Autor: Carlos González Morcillo   carlos.gonzalez@tegnix.com
 *
 * You can redistribute and/or modify this file under the terms of the
 * GNU General Public License ad published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * and later version. See <http://www.gnu.org/licenses/>.
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.  
 *********************************************************************/

package;

import util.FpsLabel;

import aze.display.TileLayer;
import aze.display.TileClip;
import aze.display.SparrowTilesheet;
import nme.Assets;
import nme.display.Sprite;
import nme.events.Event;
import nme.events.MouseEvent;
import nme.ui.Keyboard;
import nme.events.KeyboardEvent;
import nme.Lib;

class Ciclo extends Sprite {

	var _layer:TileLayer;       // Capa principal de dibujado
	var _layer2:TileLayer;       // Capa principal de dibujado
	var _character1:TileClip;    // Clip del personaje animado
	var _character2:TileClip;    // Clip del personaje animado
	var _fpstext:FpsLabel;      // Clase propia para mostrar los FPs
	var saltar:Bool;
	var altura:Int;
	var inc:Int;

	// Constructor =====================================================
	public function new() {
		super();
		haxe.Timer.delay(createScene, 150);   // Llama a "createScene"
		haxe.Timer.delay(addListeners, 150);  // Llama a "addListeners"
	}

	function createScene():Void {
		var sheetData:String = Assets.getText("assets/atlas.xml");
		var sheetData2:String = Assets.getText("assets/atlas2.xml");
		var tilesheet:SparrowTilesheet = new SparrowTilesheet(Assets.getBitmapData("assets/atlas.png"), sheetData);
		var tilesheet2:SparrowTilesheet = new SparrowTilesheet(Assets.getBitmapData("assets/atlas2.png"), sheetData2);
		_layer = new TileLayer(tilesheet);
		_layer2 = new TileLayer(tilesheet2);
		saltar = false;
		altura = 0;
		
		// Carga del Clip animado (nombre "walk" y a 16 fps)
		_character1 = new TileClip("walk", 16);  
		_character1.x = 800;  _character1.y = stage.stageHeight / 2.0; _character1.mirror = 1;
		_character2 = new TileClip("walk", 16);  
		_character2.x = 0;  _character2.y = stage.stageHeight / 2.0;
		_layer.addChild(_character1);
		_layer2.addChild(_character2);
		addChild(_layer.view);
		addChild(_layer2.view);

		// Creación del objeto FpsLabel para mostrar los FPS
		_fpstext = new FpsLabel(20, 20, 0x606060, "assets/cafeta.ttf");  
		addChild(_fpstext);
	}

	function addListeners():Void {
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
		stage.addEventListener(MouseEvent.CLICK, onMouseClicked);
		stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
	}

	// Update ==========================================================
	function goInside(c:TileClip, w:Int, h:Int, d: Float):Bool {
		// Devuelve true si está dentro o camina en dirección al escenario
		if ((c.x > w + c.width / 2) && (d > 0)) return false;
		if ((c.x < - (c.width / 2)) && (d < 0)) return false;
		return true;
	}

	function updateCharacter(fulano:TileClip):Void {
		// Ajuste del incremento en X segun la animacion
		var delta:Float = fulano.fps * 0.12;
		if (fulano.mirror == 1) delta *= -1;
		if (goInside(fulano, stage.stageWidth, stage.stageHeight, delta))
			fulano.x += delta;
	}

	function onEnterFrame(event:Event):Void {
		_fpstext.update();  // Actualizamos FPS
		if (_character1.x - _character2.x < 10) {
			_character1.mirror == 1 ? _character1.mirror = 0: _character1.mirror = 1;
			_character2.mirror == 1 ? _character2.mirror = 0: _character2.mirror = 1;
		}
		
		if (saltar) {
			if (altura < 30) {
				altura++;
				inc = -5;
			}
			else {
				if (inc < 0)
					inc = inc * (-1);
				if ( saltar && _character1.y >= stage.stageHeight / 2.0)
					saltar = false;
			}

			_character1.y += inc;
		}
		trace(altura);
		updateCharacter(_character1);  // Actualizamos el personaje
		updateCharacter(_character2);  // Actualizamos el personaje
		_layer.render();    // Despliegue de la capa principal
		_layer2.render(); 
	}
 
	// Events ==========================================================
	function onKeyPressed(event:KeyboardEvent):Void {
		switch (event.keyCode) {
			case (Keyboard.CONTROL):
				if (_character1.fps < 50) _character1.fps++;
			case (Keyboard.SPACE):
				if (_character1.fps > 2)  _character1.fps--;
			case (Keyboard.ESCAPE):
				saltar = true;
				trace("HOLA");
		}
		trace ("FPS del personaje: " + _character1.fps);
	}

	function onMouseClicked(event:MouseEvent):Void {
		_character1.mirror == 1 ? _character1.mirror = 0: _character1.mirror = 1;
		_character2.mirror == 1 ? _character2.mirror = 0: _character2.mirror = 1;
	}

	// Main ============================================================
	static public function main() {
		Lib.current.addChild(new Ciclo());
	}
}
